package com.panshi.util;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.panshi.utils.RandomCodeUtil;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class EmailUtils {

    /**
     * 发送邮箱验证码
     * @param
     * @return
     */
    public String sendEmail(JavaMailSender javaMailSender, String formEmail) {
        String value = "";
        try {
            //复杂邮件
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //组装
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);

            UUID uuid = UUID.randomUUID();

            //验证吗
            value = uuid.toString().substring(0,6);

            mimeMessageHelper.setSubject("857口腔项目实战");
            mimeMessageHelper.setText("<p>您好:</p><p>您在【857口腔项目实战】获取到的验证码如下:</p><p>【" +
                    ""+value+"】</p><p>如果不是您获取的验证码，请忽略本邮件。</p><p>为了保证您个人信息安全，请切勿把验证码给其他人。</p>" +
                    "<p>非常感谢您对【<a href='http://localhost:9998/homePage'>857口腔项目实战</a>】 的支持。</p>",true);

            mimeMessageHelper.setTo(formEmail);
            mimeMessageHelper.setFrom("cn.lvsicheng@qq.com");

            javaMailSender.send(mimeMessage);


        }catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }


    public String sendIphone(String principal) {

        String code = RandomCodeUtil.create(6);
        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GCuCN9EydDi8BkYXLRq", "FXb6LejbBuc63Iu0eOPAphSKgbXMV3");
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", principal);
        request.putQueryParameter("SignName", "857有贝口腔网");
        request.putQueryParameter("TemplateCode", "SMS_197890819");

        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(map));


        return code;
    }
}
